package cn.jeefast.rest.service.impl;

import cn.jeefast.common.entity.IrCode;
import cn.jeefast.common.utils.R;
import cn.jeefast.rest.dao.IrCodeDao;
import cn.jeefast.rest.service.IrCodeService;
import cn.jeefast.rest.util.SmsUtils;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author theodo
 * @since 2020-02-08
 */
@Service
public class IrCodeServiceImpl extends ServiceImpl<IrCodeDao, IrCode> implements IrCodeService {

    @Autowired
    private IrCodeDao codeDao;

    @Override
    public R sendCode(String phone) {
        //创建验证码
        int code = SmsUtils.getNewcode();
        //实例化存储对象
        IrCode irCode = new IrCode();
        irCode.setCodePhone(phone);
        irCode.setCodeText(code+"");
        irCode.setCodeExpir(new Date(new Date().getTime()+300000));
        irCode.setCodeUserd(0);

        //调用发送
        try {
            SendSmsResponse sendSmsResponse = SmsUtils.sendSms(phone, code + "");
            if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
                codeDao.insert(irCode);
                return R.ok("发送成功").put("data",null);
            }else {
                return R.ok(sendSmsResponse.getMessage()).put("data",null);
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return R.error("发送异常").put("data",null);
        }
    }

    @Override
    public R checkCode(String phone,String code) {
        if(phone ==null){
            return R.error("手机号有误").put("data",null);
        }

        if(code ==null){
            return R.error("验证码有误").put("data",null);
        }

        //查询
        EntityWrapper ew = new EntityWrapper();
        ew.eq("code_phone",phone);
        ew.eq("code_text",code);
        ew.orderBy("code_expir",false);
        List<IrCode> list = codeDao.selectList(ew);
        if(list.size()==0){
            return  R.error("验证码错误").put("data",null);
        }

        IrCode irCode = list.get(0);
        if(irCode.getCodeExpir().getTime()<new Date().getTime()){
            return R.error("验证码超时").put("data",null);
        }

        if(irCode.getCodeUserd()==1){
            return R.error("验证码已使用").put("data",null);
        }
        irCode.setCodeUserd(1);
        codeDao.updateById(irCode);
        return R.ok("验证成功").put("data",null);
    }
}
